package com.lishem.nettymain.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class Server {

    /***
     * 开启Netty服务
     * @param port
     */
    public void start(int port) {
        //：创建1个线程boss获取客户端链接
        EventLoopGroup boss = new NioEventLoopGroup(1);
        //：处理业务->线程->worker
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            //：创建服务端对象->ServerBootstrap
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT);
            //：给服务端对象绑定端口
            ChannelFuture future = serverBootstrap
                    //boss处理当前链接对象
                    //worker处理业务
                    .group(boss, worker)
                    //数据怎么来？什么协议？TCP
                    .channel(NioServerSocketChannel.class)  //TCP协议通道

                    /**
                     * TODO 怎么处理业务？ 增加Handler
                     * 单一业务：继承ChannelInboundHandlerAdapter处理
                     * 业务链：继承ChannelInitializer 将业务处理对象添加到Pipeline中
                     */
                    .childHandler(new MyChannelHandler()) //处理对应的业务->数据入站
                    //.childHandler(new MyChannelInitializer()) //处理对应的业务->数据入站
                    .bind(port).sync();//监听指定端口并且启动服务

            // 如果future获取到当应用对应的状态是否关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭线程池
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        Server rpcServer = new Server();
        rpcServer.start(5566);
    }
}
